<template>
	<el-form ref="formRef" :model="form" size="large" :rules="rules" class="login-content-form">
		<el-form-item class="login-animation1" prop="phone">
			<el-input text :placeholder="$t('message.mobile.placeholder1')" v-model="form.phone" clearable autocomplete="off">
				<template #prefix>
					<i class="iconfont icon-dianhua el-input__icon"></i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation2" prop="code">
			<el-col :span="15">
				<el-input text maxlength="4" :placeholder="$t('message.mobile.placeholder2')" v-model="form.code" clearable autocomplete="off">
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8">
				<el-button v-waves class="login-content-code" @click="sendSms" :loading="codeLoading">
					{{ !captchaTime ? $t('message.mobile.codeText') : captchaTime + $t('message.mobile.codeText2') }}</el-button
				>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation3">
			<el-button round type="primary" :loading="loading" v-waves class="login-content-submit" @click.prevent="submitForm(formRef)">
				<span>{{ $t('message.mobile.btnText') }}</span>
			</el-button>
		</el-form-item>
	</el-form>
</template>

<script setup lang="ts" name="loginMobile">
import { reactive, ref, computed } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { checkPhoneCount } from '/@/api/upms/sysuser';
import { getSmsCode, loginByPhone } from '/@/api/login/index';
import { Session } from '/@/utils/storage';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { formatAxis } from '/@/utils/formatTime';
import { useRoute, useRouter } from 'vue-router';
import { NextLoading } from '/@/utils/loading';
import { useI18n } from 'vue-i18n';
import { verifyPhone } from '/@/utils/toolsValidate';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
// 定义变量内容
const form = reactive({
	phone: '',
	code: '',
});
const rules = reactive({
	phone: [
		{
			required: true,
			message: '请输入手机号码',
			trigger: 'change',
		},
	],
	code: [
		{
			required: true,
			message: '请输入验证码',
			trigger: 'change',
		},
	],
});
const formRef = ref();
const captchaTime = ref(0);
const timer = ref();
const loading = ref(false);
const codeLoading = ref(false);
/**
 * 发送验证码
 */
const sendSms = () => {
	if (!form.phone) {
		return ElMessage.error('请输入手机号码');
	}
	// 验证手机号
	if (!verifyPhone(form.phone)) {
		return ElMessage.error('请输入正确的手机号');
	}
	if (captchaTime.value > 0) {
		return ElMessage.error('不能重复获取');
	}
	codeLoading.value = true;
	let params = { phone: form.phone };
	checkPhoneCount(params)
		.then((res) => {
			if (res.data.data <= 0) {
				codeLoading.value = false;
				return ElMessage.error('该手机号不存在');
			}
			getSmsCode(form.phone)
				.then((response) => {
					codeLoading.value = false;
					ElMessage.success('发送成功');
					// 通知验证码组件内部开始倒计时
					captchaTime.value = 60;
					timer.value = setInterval(() => {
						captchaTime.value--;
						if (captchaTime.value < 1) {
							clearInterval(timer.value);
							captchaTime.value = 0;
						}
					}, 1000);
				})
				.catch(() => {
					codeLoading.value = false;
				});
		})
		.catch(() => {
			codeLoading.value = false;
		});
};
/**
 * 提交按钮
 */
const submitForm = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid, fields) => {
		if (valid) {
			loading.value = true;
			loginByPhone(form.phone, form.code)
				.then(async (res) => {
					// 存储 token 到浏览器缓存
					Session.set('token', res.data.data.tokenValue);
					// 添加完动态路由，再进行 router 跳转，否则可能报错 No match found for location with path "/"
					const isNoPower = await initBackEndControlRoutes();
					// 执行完 initBackEndControlRoutes，再执行 signInSuccess
					signInSuccess(isNoPower);
				})
				.catch((error) => {
					loading.value = false;
				});
		}
	});
};
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 登录成功后的跳转
const signInSuccess = (isNoPower: boolean | undefined) => {
	if (isNoPower) {
		ElMessage.warning('抱歉，您没有登录权限');
		Session.clear();
	} else {
		// 初始化登录成功时间问候语
		let currentTimeInfo = currentTime.value;
		// 登录成功，跳到转首页
		// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
		if (route.query?.redirect) {
			router.push({
				path: <string>route.query?.redirect,
				query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
			});
		} else {
			router.push('/');
		}
		// 登录成功提示
		const signInText = t('message.signInText');
		ElMessage.success(`${currentTimeInfo}，${signInText}`);
		// 添加 loading，防止第一次进入界面时出现短暂空白
		NextLoading.start();
	}
	loading.value = false;
};
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;

	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}

	.login-content-code {
		width: 100%;
		padding: 0;
	}

	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}

}
</style>
